package com.lin.wx.pament.component.miniprogram;


import com.alibaba.fastjson2.JSON;
import com.lin.wx.pament.component.PaymentService;
import com.lin.wx.pament.component.model.Payment;
import com.lin.wx.pament.component.model.TransactionNotify;
import com.lin.wx.pament.component.model.TransactionOrder;
import com.lin.wx.pament.component.model.TransactionResult;
import com.lin.wx.pament.enums.PayType;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.partnerpayments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.*;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.AmountReq;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import com.wechat.pay.java.service.refund.model.Refund;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * 微信jsapi支付相关接口
 *
 * @author: linjiang
 * @date: 2024/12/5
 */
@Slf4j
@Service
public class WxJsapiPaymentServiceImpl implements PaymentService<Payment, TransactionNotify> {
    @Autowired(required = false)
    private RSAAutoCertificateConfig config;

    @Override
    public TransactionResult prepay(Payment payment) {
//        if (true) {
//            throw new RuntimeException("用户不存在！");
//        }
//        if (StringUtils.isEmpty(user.getOpenId())) {
//            throw new RuntimeException("小程序支付需要openId");
//        }
        // 支付服务
        JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        // 分 -> 1元 = 100分
        int money = 1;//paymentOrder.getPayAmount().multiply(new BigDecimal(100)).intValue();
        amount.setTotal(money);
        amount.setCurrency("CNY");
        request.setAmount(amount);
        request.setSpAppid("");
        request.setSpMchid("");
        request.setDescription("");
        request.setNotifyUrl("xxxx/" + PayType.WECHAT_JSAPI.getCode());
        request.setOutTradeNo("");
        Payer payer = new Payer();
        payer.setSpOpenid("");
        request.setPayer(payer);
        // 支付成功回调携带参数request.setAttach("")
        // 构造下单支付接口
        PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request, "");

        return TransactionResult.builder().orderNo("")
                .paymentDataPackage(JSON.toJSONString(response)).build();
    }

    @Override
    public TransactionResult query(TransactionOrder queryOrder) {
        // 封装请求参数
        QueryOrderByOutTradeNoRequest queryOrderReq = new QueryOrderByOutTradeNoRequest();
        queryOrderReq.setSpMchid("");
        queryOrderReq.setOutTradeNo(queryOrder.getOutTradeNo());

        // 构造查单接口
        JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();
        Transaction transaction = service.queryOrderByOutTradeNo(queryOrderReq);

        return TransactionResult.builder().orderNo(queryOrder.getOutTradeNo())
                .transactionId(transaction.getTransactionId())
                .thirdOrderStatus(transaction.getTradeState().name()).build();
    }

    @Override
    public void close(TransactionOrder closeOrder) {
        // 创建请求参数
        CloseOrderRequest closeRequest = new CloseOrderRequest();
        closeRequest.setSpMchid("");
        closeRequest.setOutTradeNo(closeOrder.getOutTradeNo());
        JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();
        service.closeOrder(closeRequest);
    }

    @Override
    public TransactionResult refunds(Payment payment) {
        // 创建请求参数
        CreateRequest request = new CreateRequest();
        AmountReq amount = new AmountReq();
        // 查询总金额
        BigDecimal totalAmount = new BigDecimal(100L);
        BigDecimal refundAmount = new BigDecimal(100L);
        if (refundAmount.compareTo(totalAmount) == NumberUtils.INTEGER_ONE) {
            throw new RuntimeException("退款金额不能超过支付总金额！");
        }
        long totalAmountDivide = totalAmount.multiply(new BigDecimal(100)).longValue();
        amount.setTotal(totalAmountDivide);
        long refundAmountDivide = refundAmount.multiply(new BigDecimal(100)).longValue();
        amount.setRefund(refundAmountDivide);
        amount.setCurrency("CNY");
        request.setAmount(amount);
        request.setOutTradeNo("");
        request.setOutRefundNo("");
        request.setReason("");
        request.setNotifyUrl("xxxx/" + PayType.WECHAT_JSAPI.getCode());
        // 构造退单接口
        RefundService service = new RefundService.Builder().config(config).build();
        Refund refund = service.create(request);

        return TransactionResult.builder().transactionId(refund.getRefundId()).build();
    }

    @Override
    public void doTransactionNotify(TransactionNotify notifyParam) {
        log.info("【微信jspai】处理支付交易回调通知【{}】", notifyParam.getOutTradeNo());
        String thirdTransactionState = notifyParam.getThirdTransactionState();
        // 修改业务订单状态
    }

    @Override
    public void doRefundNotify(TransactionNotify notifyParam) {
        log.info("【微信jspai】处理退款通知【{}】", notifyParam.getRefundNo());
    }

    @Override
    public Boolean support(String support) {
        return PayType.WECHAT_JSAPI.getCode().equals(support);
    }

}
